/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const _stringUtils = require('../utils/stringUtils');
module.exports = class extends base {
  async createTenant(body) {
    const {
      menu,
      tenantAdminUser,
      tenantAdminUsername,
      tenantAdminPassword,
      tenantName,
      isTenantSuperUser,
      tenantCode,
      createUser
    } = body;
    delete body['menu'];
    /**
     * 检查管理员账号
     */
    const userRes = await this.app.dbs.findOne('User', { username: tenantAdminUser });

    if (userRes) {
      throw new Error('管理员账号已存在！');
    }
    const res1 = await this.app.dbs.insert('Tenant', body);
    if (!tenantAdminUser) {
      return { status: 'ok', result: res1 };
    }
    /**
     * 创建管理员角色
     */
    const roleCode = _stringUtils.getCode('ROL');
    const role = {
      tenantCode,
      tenantName,
      createUser,
      createUsername: '平台系统',
      roleCode,
      roleName: '管理员',
      isAdmin: true,
      isTenantSuperUser,
      menus: menu
    };

    const res3 = await this.app.dbs.insert('Role', role);
    /**
     * 创建用户
     * @type {string}
     */
    const userCode = _stringUtils.getCode('HM');
    const user = {
      userCode,
      tenantCode,
      tenantName,
      createUser,
      createUsername: '平台系统',
      username: tenantAdminUser,
      nickname: tenantAdminUsername,
      password: tenantAdminPassword,
      userType: 'admin',
      isAdmin: true,
      roleCode,
      roleName: '管理员',
    };
    const res2 = await this.app.dbs.insert('User', user);
    /**
     * 表单的初始字段
     */
    await this.app.init.initLabelDb(tenantCode, tenantName);


    return { status: 'ok', result: body };
  }

  async findTenants() {
    const result = await this.app.dbs.find('Tenant');
    return { status: 'ok', result };
  }

  async deleteTenant(body) {
    const { tenantCode } = body;
    const result1 = await this.app.dbs.deleteMany('Tenant', { tenantCode });
    const result2 = result1 && await this.app.dbs.deleteMany('User', { tenantCode });
    const result3 = result2 && await this.app.dbs.deleteMany('Role', { tenantCode });
    const result4 = result3 && await this.app.dbs.deleteMany('DLabel', { tenantCode });
    return { status: 'ok', result: { ...result4 } };
  }

  async updateTenant(body) {
    const { tenantCode } = body;
    delete body.tenantCode;
    const result = await this.app.dbs.updateOne('Tenant', { tenantCode }, body);
    return { status: 'ok', result };
  }
};
